// pages/pay/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  getOpenId(code, cookie, money) {
    wx.request({
      url: 'https://shop.zhengjiashangye.cn/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=member.recharge.getOpenid',
      data: {
        code
      },
      header: {
        cookie
      },
      method: "GET",
      success: (res) => {
        const openid = res.data.userInfo.openid
        this.submit(cookie, money, openid)
      }
    })

  },
  submit(cookie, money, openid) {
    wx.request({
      url: 'https://shop.zhengjiashangye.cn/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=member.recharge.submit',
      method: "POST",
      data: '\r\n--XXX' +
        '\r\nContent-Disposition: form-data; name="type"' + //第一个参数key1:val1,固定写法以此类推
        '\r\n' +
        '\r\n' + 'wechat_mp' +
        '\r\n--XXX' +
        '\r\nContent-Disposition: form-data; name="money"' +
        '\r\n' +
        '\r\n' + +money +
        '\r\n--XXX' +
        '\r\nContent-Disposition: form-data; name="couponid"' +
        '\r\n' +
        '\r\n' + openid +
        '\r\n--XXX--',
      header: {
        cookie,
        'content-type': 'multipart/form-data; boundary=XXX', //XXX是分隔符的意思
      },
      success: (res) => {
        this.sendPay(res.data.result.wechat)
      }
    })
  },
  sendPay(options) {
    console.log(options)
    wx.requestPayment({
      nonceStr: options.nonceStr,
      package: options.package,
      paySign: options.paySign,
      timeStamp: options.timeStamp,
      signType: options.signType,
      success: function (res) {
        console.log('res: ', res);
        wx.showToast({
          title: '支付成功',
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/index/index',
          })
        }, 2000);
      },
      fail: function (err) {
        console.log('err: ', err);
        wx.showToast({
          title: '支付失败',
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/index/index',
          })
        }, 2000);
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    options.package = decodeURIComponent(options.package)
    options.cookie = decodeURIComponent(options.cookie)
    // 登录 获取code
    wx.login({
      timeout: 2000,
    }).then((res) => {
      this.getOpenId(res.code, options.cookie, options.money)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log(this)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})